#include "BGClipLayer.h"
#include "common.h"
using namespace fireplane;

bool BGClipLayer::init()
{
	bool ret = CCLayer::init();
	_enable = true;
	return ret;
}


void BGClipLayer::setClipRect(cocos2d::CCRect clipRect)
{
	this->clipRect = clipRect;
}

void BGClipLayer::visit() 
{
	if(_enable == false)
		return CCLayer::visit();
    
	if (!this->isVisible())
		return;
    
	glPushMatrix();
    
	glEnable(GL_SCISSOR_TEST);
    
	CCDirector *director = CCDirector::sharedDirector();
	CCSize size = Common::getWinSize();
    
	CCRect rect;
	CCRect scissorRect;
    
	// transform the clipping rectangle to adjust to the current screen
	// orientation: the rectangle that has to be passed into glScissor is
	// always based on the coordinate system as if the device was held with the
	// home button at the bottom. the transformations account for different
	// device orientations and adjust the clipping rectangle to what the user
	// expects to happen.

     rect.size = CCSizeMake(clipRect.size.width ,clipRect.size.height);
     rect.origin = ccp(clipRect.origin.x,clipRect.origin.y);
     scissorRect = rect;


	CCAffineTransform transform = this->getParent()->nodeToWorldTransform();
	scissorRect = CCRectApplyAffineTransform(scissorRect,transform);
    
#if 0//CC_TARGET_PLATFORM == CC_PLATFORM_WIN32
	glScissor((GLsizei)scissorRect.origin.x, (GLsizei)scissorRect.origin.y,
              (GLsizei)scissorRect.size.width, (GLsizei)scissorRect.size.height);
#else
	 CCDirector::sharedDirector()->getOpenGLView()->setScissorInPoints(
			scissorRect.origin.x, scissorRect.origin.y,
			scissorRect.size.width, scissorRect.size.height);
#endif
	
    
	CCLayer::visit();
    
	glDisable(GL_SCISSOR_TEST);
	glPopMatrix();
}

BGClipLayer* BGClipLayer::node()
{
	BGClipLayer *pRet = new BGClipLayer();
	if (pRet && pRet->init())
	{
		pRet->autorelease();
		return pRet;
	}
	else
	{
		CC_SAFE_DELETE(pRet);
        return NULL;
        
	}
}

CCRect BGClipLayer::getClipRect()
{
	return this->clipRect;
}
